<?php


use Illuminate\Database\Capsule\Manager as DB;

class Dianpu_ApplyController extends CommonController
{
    #[申请列表]
    public function indexAction()
    {
        $query = \app\modules\Admin\models\dianpuapplyModel::query()->where('member_id', $this->user->id);
        $mode = $this->get('mode', 'all');
        switch ($mode){
            case 'reject':
                $query->where('status', '=', -1);
                break;
            case 'waiting':
                $query->where('status', '=', 0);
                break;
            case 'accepted':
                $query->where('status', '=', 1);
                break;
        }
        $total = $query->count();
        $query = $query->orderByDesc('created_at');
        $page = $this->get('page', 1);
        $limit = $this->get('rows', 10);
        $offset = ($page - 1) * $limit;
        $query = $query->offset($offset)->limit($limit);
        $rows = $query->get();
        json(['total' => $total, 'rows' => $rows->toArray()]);
    }

    #[查看申请]
    public function detailAction()
    {
        try {
            $apply = \app\modules\Admin\models\dianpuapplyModel::query()->where('member_id', $this->user->id)->firstOrFail();
            $new_apply = $this->checkBuyGoods($apply);
            json(['code'=> 1, 'data'=>$new_apply]);
        }catch (Exception $e){
            json(['code' => 300, 'msg' => '申请不存在']);
            exit;
        }
    }
	
	#[查看店铺]
    public function infoAction()
    {
        try {
            $apply = dianpuModel::query()->where('member_id', $this->user->id)->firstOrFail();
            $new_apply = $this->checkBuyGoods($apply);
            json(['code'=> 1, 'data'=>$new_apply]);
        }catch (Exception $e){
            json(['code' => 0, 'msg' => '店铺不存在']);
            exit;
        }
    }

    #[检查是否需要购买资格商品]
    private function checkBuyGoods($apply)
    {
        $dianpu_enable_goods_id = configModel::query()->where('type',19)->where('key','dianpufenhong_enbale_goods_id')->value('value');
        //是否需要购买资格商品 0=不需要，1=需要
        $need_buy_goods = 0;
        if($dianpu_enable_goods_id>0){
            $orders = orderitemModel::query()->where('member_id', $this->user->id)
                                    ->where('goods_id', $dianpu_enable_goods_id)
                                    ->where('aftersale_status','<=',0)
                                    ->where('refund_status','<=',0)
                                    ->whereHas('order', function ($orderWhere){
                                        $orderWhere->where('status', '>', 0);
                                    })->count('id');
            if($orders){
                $need_buy_goods = 0;
            }else{
                $need_buy_goods = 1;
            }
        }
        $new_apply = $apply->toArray();
        $new_apply['need_buy_goods'] = $need_buy_goods;
        if($need_buy_goods){
            $new_apply['dianpu_agent_goods_id'] = $dianpu_enable_goods_id;
        }
        return $new_apply;
    }

    #[修改申请]
    public function editAction()
    {
        if (!$this->isPost()){
            json(['code' => 0, 'msg' => '必须POST']);
            exit;
        }
        $id = $this->get('id');
        if (!is_numeric($id)){
            json(['code' => 0, 'msg' => '非法请求', $id]);
            exit;
        }
        $params = $this->postData;
        try {
            Validate::check($params, [
                'name' => [
                    'role' => 'required|maxlength:20|minlength:4',
                    'msg' => '店铺名称',
                ],
                'realname' => [
                    'role' => 'required|maxlength:10|minlength:2',
                    'msg' => '法人代表姓名',
                ],
                'company_name' => [
                    'role' => 'required|maxlength:20|minlength:2',
                    'msg' => '公司名称',
                ],
                'phone' => [
                    'role' => 'required|maxlength:20|minlength:7',
                    'msg' => '联系电话',
                ],
                'area_name' => [
                    'role' => 'required',
                    'msg' => '商家所在地区',
                ],
                'address' => [
                    'role' => 'required',
                    'msg' => '商家详细地址',
                ],
                'company_bank' => [
                    'role' => 'required',
                    'msg' => '对公帐户开户行',
                ],
                'company_bank_name' => [
                    'role' => 'required',
                    'msg' => '对公帐户名称',
                ],
                'company_bank_card' => [
                    'role' => 'required',
                    'msg' => '对公帐户帐号',
                ],
                'company_license_image' => [
                    'role' => 'required',
                    'msg' => '企业营业执照',
                ],
                'company_representative_idcard_front_image' => [
                    'role' => 'required',
                    'msg' => '法定代表人身份证头像面照片',
                ],
                'company_representative_idcard_reverse_image' => [
                    'role' => 'required',
                    'msg' => '法定代表人身份证国徽面照片',
                ],
                //                'company_representative_idcard_hand_image' => [
                //                    'role' => 'required',
                //                    'msg' => '法定代表人身份证手持照片',
                //                ],
            ]);
            if(
                \app\modules\Admin\models\dianpuapplyModel::query()->where('company_name', '=', $params['company_name'])->where('id', '<>', $id)->exists()
                ||
                dianpuModel::query()->where('company_name', '=', $params['company_name'])->exists()
            ){
                throw new Exception('企业名称已经被占用', 30001);
            }
            if(isset($params['name'])){
                if(
                    \app\modules\Admin\models\dianpuapplyModel::query()->where('name', '=', $params['name'])->where('id', '<>', $id)->exists()
                    ||
                    \app\modules\Admin\models\dianpuModel::query()->where('name', '=', $params['name'])->exists()
                ){
                    throw new Exception('店铺名称已经被占用', 30001);
                }
            }else{
                $params['name'] = $params['company_name'].'的店铺';
            }
            $apply = \app\modules\Admin\models\dianpuapplyModel::query()->findOrFail($id);
            if($apply->member_id !== $this->user->id){
                throw new Exception('无法修改别人的申请', 30001);
            }
            if($apply->status === 1){
                throw new Exception('申请已经处理，不能修改', 30001);
            }
            $apply->realname = $params['realname'];
            $apply->company_name = $params['company_name'];
            $apply->phone = $params['phone'];
            $apply->province_name = $params['province_name'];
            $apply->city_name = $params['city_name'];
            $apply->area_name = $params['area_name'];
            $apply->province_id = $params['province_id'];
            $apply->city_id = $params['city_id'];
            $apply->area_id = $params['area_id'];
            $apply->address = $params['address'];
            $apply->company_bank = $params['company_bank'];
            $apply->company_bank_name = $params['company_bank_name'];
            $apply->company_bank_card = $params['company_bank_card'];
            $apply->company_license_image = $params['company_license_image'];
            $apply->company_representative_idcard_front_image = $params['company_representative_idcard_front_image'];
            $apply->company_representative_idcard_reverse_image = $params['company_representative_idcard_reverse_image'];
            $apply->status = 0;
            $apply->updated_at = timestamp();
            if($apply->save()){
                json(['code' => 1, 'msg' => '申请修改成功！']);
                exit;
            }else{
                json(['code' => 0, 'msg' => '申请修改失败！']);
                exit;
            }
        }catch (Exception $e){
            json(['code' => 0, 'msg' => ($e->getCode() !== 30001)?'申请不存在':$e->getMessage()]);
            exit;
        }
    }

    #[取消申请]
    public function cancelAction()
    {
        if(!$this->isPost()){
            json(['code' => 0, 'msg' => '请求出错！']);
            exit;
        }
        $id = $this->get('id');
        try {
            $apply = \app\modules\Admin\models\dianpuapplyModel::query()->findOrFail($id);
            if($apply->member_id !== $this->user->id){
                throw new Exception('取消别人的申请', 30001);
            }
            if($apply->status !== 0){
                throw new Exception('申请已经处理，不能取消', 30001);
            }
            if($apply->delete()){
                json(['code' => 1, 'msg' => '申请取消成功']);
                exit;
            }else{
                json(['code' => 0, 'msg' => '申请取消失败，请重试']);
                exit;
            }
        }catch (Exception $e){
            json(['code' => 0, 'msg' => ($e->getCode() !== 30001)?'申请不存在':$e->getMessage()]);
            exit;
        }
    }

    #[创建申请]
    public function createAction()
    {
        if(!$this->isPost()){
            json(['code' => 0, 'msg' => '请求出错！']);
            exit;
        }
        $params = $this->postData;
        try {
            Validate::check($params, [
                'realname' => [
                    'role' => 'required|maxlength:10|minlength:2',
                    'msg' => '法人代表姓名',
                ],
                'company_name' => [
                    'role' => 'required|maxlength:20|minlength:2',
                    'msg' => '公司名称',
                ],
                'phone' => [
                    'role' => 'required|maxlength:20|minlength:7',
                    'msg' => '联系电话',
                ],
                'area_name' => [
                    'role' => 'required',
                    'msg' => '商家所在地区',
                ],
                'address' => [
                    'role' => 'required',
                    'msg' => '商家详细地址',
                ],
                'company_bank' => [
                    'role' => 'required',
                    'msg' => '对公帐户开户行',
                ],
                'company_bank_name' => [
                    'role' => 'required',
                    'msg' => '对公帐户名称',
                ],
                'company_bank_card' => [
                    'role' => 'required',
                    'msg' => '对公帐户帐号',
                ],
                'company_license_image' => [
                    'role' => 'required',
                    'msg' => '企业营业执照',
                ],
                'company_representative_idcard_front_image' => [
                    'role' => 'required',
                    'msg' => '法定代表人身份证头像面照片',
                ],
                'company_representative_idcard_reverse_image' => [
                    'role' => 'required',
                    'msg' => '法定代表人身份证国徽面照片',
                ],
                //                'company_representative_idcard_hand_image' => [
                //                    'role' => 'required',
                //                    'msg' => '法定代表人身份证手持照片',
                //                ],
            ]);
            $myApply = \app\modules\Admin\models\dianpuapplyModel::query()->where('member_id', '=', $this->user->id)->first();
            if($myApply){
                throw new Exception('申请已存在');
            }
            if(\app\modules\Admin\models\dianpuapplyModel::query()->where('company_name', '=', $params['company_name'])->exists()
                ||
                dianpuModel::query()->where('company_name', '=', $params['company_name'])->exists()){
                throw new Exception('企业名称已经补占用');
            }
            unset($params['id']);
            $this->cleanTableColumn('dianpu_apply', $params);
            $params['member_id'] = $this->user->id;
            $params['name'] = $params['company_name'].'的店铺';
            $params['created_at'] = timestamp();
            $params['updated_at'] = $params['created_at'];
            $params['company_representative_idcard_hand_image'] = '';
            $res = DB::transaction(function () use ($params){
                return DB::table('dianpu_apply')->insert($params);
            });
            if($res){
                json(['code' => 1, 'msg' => '申请店铺代理成功，请保持联系电话畅通!']);
                exit;
            }else{
                json(['code' => 0, 'msg' => '申请提交失败，请刷新后再试！']);
                exit;
            }
        } catch (Exception $e) {
            json(['code' => 0, 'msg' => $e->getMessage()]);
            exit;
        }

    }
}